<template>
  <div class="index-wrapper">
    <div class="index-sub-title">
      <NewSelection @change="handleChange" :roleOption="user" :showLine="false">
      </NewSelection>
    </div>
    <div class="index-charts">
      <div class="warning-box">
        <div class="warning-control">
          <img src="../../assets/error-level.png" alt="" />
          <span>风险</span>
        </div>
        <span>{{ (statusData[0] && statusData[0].value) || 0 }}</span>
      </div>
      <PieCharts :mapData="mapData" :title="lineTitle" :isError="false"></PieCharts>
      <PieCharts :mapData="statusData" :title="statusTitle" :isError="true"></PieCharts>
      <!-- <PieCharts :mapData="mapData" :title="lineTitle"></PieCharts> -->
    </div>
    <Map
      :markers="deviceList"
      @lookDetail="handleLookDetail"
      :polylinePath="polylinePath"
    ></Map>
    <div class="detail-box" v-if="showDetail">
      <Detail :item="item" @closeDetail="handleClose">
        <template #charts>
          <span v-show="showChart1">近一月电流趋势图</span>
          <Charts :echartsId="chartId1" :options="options[0]" v-show="showChart1" chartUnitText="A"></Charts>
          <span v-show="showChart2">近一月电压趋势图</span>
          <Charts :echartsId="chartId2" :options="options[1]" v-show="showChart2" chartUnitText="V"></Charts>
          <span>近一月三相温度趋势图</span>
          <Charts :echartsId="chartId3" :options="options[2]" chartUnitText="℃"></Charts>
          <span>近一月环境温度趋势图</span>
          <Charts :echartsId="chartId4" :options="options[3]" chartUnitText="℃"></Charts>
          <span>近一月环境湿度趋势图</span>
          <Charts :echartsId="chartId5" :options="options[4]" chartUnitText="%"></Charts>
        </template>
        <template #btn>
          <el-button
            class="address"
            @click="routeHere(item)"
            icon="el-icon-location-outline"
            >导航</el-button
          >
        </template>
      </Detail>
    </div>
  </div>
</template>
<script>
import PieCharts from "@/components/pieCharts";
import Map from "./map";
import NewSelection from "@/components/newSelection";
import Detail from "./detail";
import Charts from "@/components/echarts";
import { mapGetters } from "vuex";
import {
  deviceMapList,
  getRouteGroup,
  getDeviceStatus,
  getDeviceDetail,
} from "@/api";
export default {
  name: "deviceMap",
  components: {
    Map,
    PieCharts,
    NewSelection,
    Detail,
    Charts,
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
  },
  data() {
    return {
      mapData: [],
      lineTitle: "设备线路统计",
      statusTitle: "设备运行统计",
      statusData: [],
      item: {},
      deviceList: [],
      showDetail: false,
      polylinePath: [],
      pieData: [],
      chartId1: `chartId1${Math.random(0, 1)}`,
      chartId2: `chartId2${Math.random(0, 1)}`,
      chartId3: `chartId3${Math.random(0, 1)}`,
      chartId4: `chartId4${Math.random(0, 1)}`,
      chartId5: `chartId5${Math.random(0, 1)}`,
      options: [],
      showChart1:true,
      showChart2:true,
    };
  },
  created() {
    this.getDeviceMapList(this.user.countryId);
    this.getpieData(this.user.countryId);
    this.getDeviceStatus(this.user.countryId);
  },
  methods: {
    // 监听区域变化 更新地图的设备点
    handleChange(params1, params2) {
      this.getDeviceMapList(params1[2]);
      this.getpieData(params1[2]);
      this.getDeviceStatus(params1[2]);
    },
    getpieData(id) {
      getRouteGroup({
        countryId: id,
      })
        .then((res) => {
          if (res.statusCode == 200) {
            if (res.data && res.data.length > 0) {
              this.mapData = res.data.map((item) => {
                return {
                  value: item.deviceCount,
                  name: item.routeName,
                };
              });
            }
          } else {
            this.$message(res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取地图设备列表
    getDeviceMapList(id) {
      deviceMapList({
        countryId: id,
      })
        .then((res) => {
          if (res.statusCode == 200) {
            this.deviceList = res.data;
            this.deviceList.forEach(item => {
              if(item.attachUrl && item.attachUrl.indexOf('http') < 0) {
                item.attachUrl = $globalUrl + item.attachUrl
              }
            })
            this.polylinePath = this.groups(this.deviceList, "routeId");
            console.log(this.polylinePath);
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleClose() {
      this.showDetail = false;
    },
    // 绑定点击事件
    handleLookDetail(val) {
      this.item = val;
      this.viewDetail(val.deviceid);
    },
    // 查询单个设备的详情
    viewDetail(deviceId) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      console.log(deviceId);
      getDeviceDetail(deviceId)
        .then((res) => {
          loading.close();
          if (res.statusCode == 200) {
            this.showDetail = true;
            let targetItem = res.data.resData;
            // 异常处理
            if (!targetItem || targetItem.length === 0) {
              this.showChart1 = false;
              this.showChart2 = false;
              return false;
            }
            this.showChart1 = true;
            this.showChart2 = true;
            if(targetItem[0].acurrent == 0) {
                this.showChart1 = false;
            }
            if(targetItem[0].avoltage == 0) {
                this.showChart2 = false;
            }
            let cate = targetItem.map((item) => {
              return item.createDate.split(" ")[0];
            });
            let acurrentData = targetItem.map((item) => {
              return parseInt(item.acurrent) ;
            });
            let bcurrentData = targetItem.map((item) => {
              return parseInt(item.bcurrent) ;
            });
            let ccurrentData = targetItem.map((item) => {
              return parseInt(item.ccurrent) ;
            });
            let avoltageData = targetItem.map((item) => {
              return parseInt(item.avoltage) ;
            });
            let bvoltageData = targetItem.map((item) => {
              return parseInt(item.bvoltage) ;
            });
            let cvoltageData = targetItem.map((item) => {
              return parseInt(item.cvoltage) ;
            });
            let atemperatureData = targetItem.map((item) => {
              return parseInt(item.atemperature) ;
            });
            let btemperatureData = targetItem.map((item) => {
              return parseInt(item.btemperature) ;
            });
            let ctemperatureData = targetItem.map((item) => {
              return parseInt(item.ctemperature) ;
            });
            let temperatureData = targetItem.map((item) => {
              return parseInt(item.temperature) ;
            });
            let humidityData = targetItem.map((item) => {
              return parseInt(item.humidity) ;
            });
            const option1 = {
              dataCate: ["A相电流", "B相电流", "C相电流"],
              categories: cate,
              data1: acurrentData,
              data2: bcurrentData,
              data3: ccurrentData,
            };
            const option2 = {
              dataCate: ["A电缆电压", "B电缆电压", "C电缆电压"],
              categories: cate,
              data1: avoltageData,
              data2: bvoltageData,
              data3: cvoltageData,
            };
            const option3 = {
              dataCate: ["A电缆温度", "B电缆温度", "C电缆温度", "环境温度"],
              categories: cate,
              data1: atemperatureData,
              data2: btemperatureData,
              data3: ctemperatureData,
            };
            const option4 = {
              dataCate: ["环境温度"],
              categories: cate,
              data1: temperatureData,
            };
            const option5 = {
              dataCate: ["环境湿度"],
              categories: cate,
              data1: humidityData,
            };
            this.options = [option1, option2, option3, option4, option5];
            // this.options = [option1, option2];
            console.log("this.options", this.options);
          } else {
            this.$message(res.msg);
          }
        })
        .catch((err) => {
          loading.close();
          console.log(err);
        });
    },
    groups(arr, key) {
      let map = {},
        dest = [];
      for (let i = 0; i < arr.length; i++) {
        let ai = arr[i];
        if (!map[ai[key]]) {
          dest.push({
            key: ai[key],
            data: [ai],
          });
          map[ai[key]] = ai;
        } else {
          for (let j = 0; j < dest.length; j++) {
            let dj = dest[j];
            if (dj.key == ai[key]) {
              dj.data.push(ai);
              break;
            }
          }
        }
      }
      return dest;
    },
    getDeviceStatus(id) {
      getDeviceStatus({
        countryId: id,
      })
        .then((res) => {
          if (res.statusCode == 200) {
            this.statusData = [
              {
                value: res.error || "",
                name: "异常",
              },
              {
                value: res.normal || "",
                name: "在线",
              },
              {
                value: res.offline || "",
                name: "离线",
              },
            ];
          } else {
            this.$message(res.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 去这里
    routeHere(item) {
      // this.$router.push({
      //   path:"/MapDriveRoute",
      //   query: {
      //     Lng:item.longitude,
      //     lat:item.latitude
      //   }
      // })
      window.location.href = "https://map.baidu.com/";
    },
  },
};
</script>
<style lang="less" scoped>
.index-wrapper {
  position: relative;
  overflow: hidden;
  background: rgba(27, 35, 45, 1);
}
.index-sub-title {
  position: absolute;
  top: 80px;
  left: 35px;
  z-index: 10;
}
.index-charts {
  position: absolute;
  left: 20px;
  top: 140px;
  z-index: 10;
  background: rgba(27, 35, 45, 0.9);
  display: flex;
  flex-direction: column;
  .warning-box {
    width: 430px;
    display: flex;
    justify-content: space-between;
    height: 52px;
    align-items: center;
    color: #ea615d;
    box-sizing: border-box;
    padding: 0 57px;
    font-size: 36px;
    margin-bottom: 20px;
    .warning-control {
      width: 110px;
      display: flex;
      align-items: center;
      span {
        margin-left: 20px;
        font-size: 20px;
        color: #fff;
      }
    }
  }
}
.detail-box {
  position: absolute;
  right: 40%;
  top: 50%;
  transform: translateY(-50%);
  .address {
    width: 287px;
    height: 37px;
    background: #4f6fcc;
    border-radius: 5px;
    color: #fff;
    margin: 0 auto;
  }
}
</style>
